# Copyright (c) 2024, lanlian and contributors
# For license information, please see license.txt

import json

import frappe
from frappe import _, msgprint
from frappe.model.mapper import get_mapped_doc
from frappe.utils import cint, cstr, flt
from frappe.model.document import Document


class EMSFaultReport(Document):
	def before_save(self):
		# 保存时自动写month字段, 目的是统计报表时直接可用
		# frappe.db.set_value(self.doctype, self.name, {"month": self.happen_date.month})
		self.test_month = 9
		

	def on_submit(self):
		self.set_repair_status()
		# 更新卡片管理状态为keep in repair
		frappe.db.set_value('EMS Equipment Card', self.equipment_number, {'card_manager_status': 'keep in repair'})

	def set_repair_status(self, repair_status=None):
		"""Get and update status"""
		if not repair_status:
			repair_status = self.get_repair_status()
		self.db_set("repair_status", repair_status)

	def get_repair_status(self):
		"""Returns status based on task, repair..."""
		if self.docstatus == 0:
			repair_status = "Open"
		elif self.docstatus == 1:
			repair_status = "Submitted"

			if frappe.db.exists({"doctype": "EMS Fault Repair", "ems_fault_report": self.name, "docstatus": ["in", (0,1)] }):
				repair_status = "Completed"
			elif frappe.db.exists({"doctype": "EMS Fault Repair Task", "ems_fault_report": self.name, "docstatus": ["in", (0,1)] }):
				repair_status = "Scheduled"
		elif self.docstatus == 2:
			repair_status = "Cancelled"
		return repair_status


# 故障报修下推故障报修派工
@frappe.whitelist()
def make_fault_report_task(source_name, target_doc=None, args=None):
	doc = get_mapped_doc(
		"EMS Fault Report",
		source_name,
		{
			"EMS Fault Report": {
				"doctype": "EMS Fault Repair Task",
				"field_map": {},
				"validation": {"docstatus": ["=", 1],},
			},
		},
		target_doc,
		ignore_permissions=True,
	)

	return doc


# 故障报修单下推外部维修单
@frappe.whitelist()
def make_external_maintenance(source_name, target_doc=None, args=None):
	doc = get_mapped_doc(
		"EMS Fault Report",
		source_name,
		{
			"EMS Fault Report": {
				"doctype": "EMS External Maintenance",
				"field_map": {},
				"validation": {"docstatus": ["=", 1]},
			},
		},
		target_doc,
		ignore_permissions=True,
	)

	return doc